package com.example.administrator.caigou51.control;


import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.GradientDrawable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ab.util.AbViewUtil;
import com.alibaba.fastjson.JSON;
import com.example.administrator.caigou51.EventBusClass.UpdateShopCarFragment;
import com.example.administrator.caigou51.EventBusClass.UpdateShopCarRedCount;
import com.example.administrator.caigou51.R;
import com.example.administrator.caigou51.activity.CheckOrderActivity;
import com.example.administrator.caigou51.activity.GBaseActivity;
import com.example.administrator.caigou51.activity.LoginActivity;
import com.example.administrator.caigou51.activity.StoreManagerActivity;
import com.example.administrator.caigou51.bean.GoodsDetailBean;
import com.example.administrator.caigou51.bean.ShopCarBean;
import com.example.administrator.caigou51.global.App;
import com.example.administrator.caigou51.global.Constant;
import com.example.administrator.caigou51.recyclerCard.cardView.GoodsDetailCardView;
import com.example.administrator.caigou51.request.BaseResponse;
import com.example.administrator.caigou51.request.ICallBackForRequestServer;
import com.example.administrator.caigou51.request.RequestServerManager;
import com.example.administrator.caigou51.util.AnimUtils;
import com.example.administrator.caigou51.util.ImageUtil;
import com.example.administrator.caigou51.util.MyMathUtial;
import com.example.administrator.caigou51.util.ToastUtil;
import com.example.administrator.caigou51.widget.dialog.SweetDialogManager;
import com.example.administrator.caigou51.widget.labelListView.BaseLabelListView;
import com.example.administrator.caigou51.widget.labelListView.GameLabel;
import com.example.administrator.caigou51.widget.labelListView.IOnItemClickListener;
import com.example.administrator.caigou51.widget.labelListView.LabelListView;


import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import cn.pedant.SweetAlert.SweetAlertDialog;
import de.greenrobot.event.EventBus;


/**
 * Create custom Dialog windows for your application Custom dialogs rely on
 * custom layouts wich allow you to create and use your own look & feel.
 * <p/>
 * Under GPL v3 : http://www.gnu.org/licenses/gpl-3.0.html
 *
 * @author antoine vianey
 */
public class DialogGoodsBuy extends Dialog implements View.OnClickListener {

    private Context context;
    private RelativeLayout relativeLayoutTitle;
    private TextView textViewName,textViewTotalCount,textViewTotal;
    private EditText editTextCount;
    private TextView textViewIconMoney;
    private ImageView imageViewClose;
    private ImageView imageViewGoods;
    private com.example.administrator.caigou51.widget.labelListView.LabelListView label_list_view_guige;
    private TextView textViewKuCun;
    private LinearLayout textViewReduce;
    private TextView textViewAdd,textViewPrice;
    private LinearLayout linearLayoutJoin;
    private LinearLayout linearLayoutBuy;
    GoodsDetailBean goodsDetailBean;
    public static final int BugNowTag=99;
    public static final int AddCar=88;
    public  int currentTag=0;
    private View viewReduce;
    private int goodsCount=1;
    public DialogGoodsBuy(Context context, GoodsDetailBean goodsDetailBean,int tag) {
       super(context, R.style.dialogBuyGoods);
       // super(context);
        currentTag=tag;
        this.context=context;
        this.goodsDetailBean=goodsDetailBean;
        setCustomDialog();

      //  initData(label_list_view_guige);
    }

    public DialogGoodsBuy(Context context, int theme) {
        super(context, theme);
        this.context=context;
    }

    @Override
    public void setOnDismissListener(OnDismissListener listener) {
        BaseLabelListView.isDialog=false;
        super.setOnDismissListener(listener);
    }

    private void setCustomDialog() {
        View mView = LayoutInflater.from(getContext()).inflate(R.layout.dialog_goods_buy, null);
        AbViewUtil.scaleContentView((ViewGroup) mView);
        BaseLabelListView.isDialog=true;
        relativeLayoutTitle = (RelativeLayout) mView.findViewById(R.id.relativeLayoutTitle);
        textViewName = (TextView) mView.findViewById(R.id.textViewName);
        textViewTotalCount= (TextView) mView.findViewById(R.id.textViewTotalCount);
        viewReduce= mView.findViewById(R.id.viewReduce);
        textViewTotal= (TextView) mView.findViewById(R.id.textViewTotal);
        textViewPrice= (TextView) mView.findViewById(R.id.textViewPrice);
        editTextCount = (EditText) mView.findViewById(R.id.editTextCount);

        editTextCount.setText("1");
        editTextCount.setSelection(editTextCount.getText().toString().length());
        editTextCount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                try {
                    String str = editTextCount.getText().toString();
                    int i= Integer.parseInt(str);
                    goodsCount=i;
                    int kucun=Integer.parseInt(goodsDetailBean.getAmount());
                    if (i>kucun) {
                        goodsCount=kucun;
                        editTextCount.setText(goodsCount+"");
                    }
                    compluteTotal(goodsCount);
                }catch (Exception e)
                {
                    goodsCount=1;
                    editTextCount.setText(1+"");
                    compluteTotal(goodsCount);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        textViewIconMoney = (TextView) mView.findViewById(R.id.textViewIconMoney);
        imageViewClose = (ImageView) mView.findViewById(R.id.imageViewClose);
        imageViewGoods = (ImageView) mView.findViewById(R.id.imageViewGoods);
        label_list_view_guige = (com.example.administrator.caigou51.widget.labelListView.LabelListView)mView.findViewById(R.id.label_list_view_guige);
        textViewKuCun = (TextView)mView.findViewById(R.id.textViewKuCun);
        textViewReduce = (LinearLayout) mView.findViewById(R.id.textViewReduce);textViewReduce.setOnClickListener(this);
        textViewAdd = (TextView) mView.findViewById(R.id.textViewAdd);textViewAdd.setOnClickListener(this);
        linearLayoutJoin = (LinearLayout) mView.findViewById(R.id.linearLayoutJoin);linearLayoutJoin.setOnClickListener(this);
        linearLayoutBuy = (LinearLayout) mView.findViewById(R.id.linearLayoutBuy);

        imageViewClose.setOnClickListener(this);
        linearLayoutBuy.setOnClickListener(this);


        textViewName.setText("已选 : "+goodsDetailBean.getTitle());
        //判断促销信息
        if (GoodsDetailCardView.Tag_PuTong.equals(goodsDetailBean.getPromotion()))
        {

            textViewPrice.setText(goodsDetailBean.getShip_price()+"");
        } else if (GoodsDetailCardView.Tag_ZhiJiang.equals(goodsDetailBean.getPromotion()))
        {
            textViewPrice.setText(goodsDetailBean.getPromotion_price()+"");
        }else if (GoodsDetailCardView.Tag_ZheKou.equals(goodsDetailBean.getPromotion()))
        {
            textViewPrice.setText(goodsDetailBean.getPromotion_price()+"");
        }else
        {
            textViewPrice.setText(goodsDetailBean.getShip_price()+"");
        }

        textViewKuCun.setText("库存: "+goodsDetailBean.getAmount()+"");

        if (goodsDetailBean.getImages()!=null && !TextUtils.isEmpty(goodsDetailBean.getImages().get(0))) {
            App.displayImageHttpOrFile(goodsDetailBean.getImages().get(0), imageViewGoods, ImageUtil.OptionsActivity());
        }

        ArrayList<GameLabel> labelListGuige = new ArrayList<GameLabel>();
        GameLabel label = new GameLabel();
        label.name = goodsDetailBean.getProduct_spec();
        label.textColor = "78828b";
        label.backgroudColor = "f7f9f8";
        label.strokeColor = "f5f5f5";
        labelListGuige.add(label);
        label_list_view_guige.setData(labelListGuige);


        label_list_view_guige.setIOnItemClickListener(new IOnItemClickListener() {

            @Override
            public void onClick(String name, int position) {

/*                Toast.makeText(context,
                        "标签内容：" +labelListViewGuige.getChildCount()+ name + "   位置:" + position,
                        Toast.LENGTH_SHORT).show();*/
                for (int i=0;i<label_list_view_guige.getTextViewList().size();i++)
                {
                    TextView textView= label_list_view_guige.getTextViewList().get(i);
                    textView.setBackgroundDrawable(getDrawblRadius20(R.color.color_f5f5f5));
                    textView.setTextColor(context.getResources().getColor(R.color.color_666666));
                    //textView.setTextSize(AbViewUtil.scaleTextValue(App.getInstance().getApplicationContext(),12));
                }
                TextView textView= label_list_view_guige.getTextViewList().get(position);
                textView.setBackgroundDrawable(getDrawblRadius20(R.color.color_1ca146));
                textView.setTextColor(context.getResources().getColor(R.color.white));
              //  textView.setTextSize(AbViewUtil.scaleTextValue(App.getInstance().getApplicationContext(),12));
            }
        });
        super.setContentView(mView);

        if (currentTag==BugNowTag)
        {
            linearLayoutJoin.setVisibility(View.GONE);

            compluteTotal(1);
        }else{
            linearLayoutBuy.setVisibility(View.GONE);

            compluteTotal(goodsCount);
        }
    }

    private GradientDrawable getDrawblRadius20(int color) {
        GradientDrawable mGradientDrawable= new GradientDrawable();
        mGradientDrawable.setColor(context.getResources().getColor(
                color));
        mGradientDrawable.setCornerRadius(dip2px(20));
        return mGradientDrawable;
    }
    private int dip2px(float dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    private void compluteTotal(int count)
    {



        textViewTotalCount.setText(count+"");
        textViewTotal.setText(MyMathUtial.saveTwoXiaoShu(count* Float.parseFloat(textViewPrice.getText().toString())));

        if (count==1)
        {
            viewReduce.setBackgroundColor(context.getResources().getColor(R.color.color_d4d4d4));
        }else
        {
            viewReduce.setBackgroundColor(context.getResources().getColor(R.color.color_78828b));
        }
        int kucun=Integer.parseInt(goodsDetailBean.getAmount());
        if (kucun>count)
        {
            textViewAdd.setTextColor(context.getResources().getColor(R.color.color_78828b));
        }else
        {
            textViewAdd.setTextColor(context.getResources().getColor(R.color.color_d4d4d4));
        }

       // editTextCount.setText(editCount);
       // textViewTotalCount.setText(count2);
       // textViewTotal.setText(count* Integer.parseInt(goodsDetailBean.getPrice()));
    }
    @Override
    public void onClick(View v) {
        switch (v.getId())
        {
            case R.id.textViewReduce:

                if (goodsCount>1)
                {
                    goodsCount=goodsCount-1;
                    editTextCount.setText(goodsCount+"");
                    compluteTotal(goodsCount);
                  }else
                  {
                      ToastUtil.showToast("不能再减了");
                   }


                break;
            case R.id.textViewAdd:
                int kucun=Integer.parseInt(goodsDetailBean.getAmount());
                 if (kucun>goodsCount)
                 {
                     goodsCount=goodsCount+1;
                     editTextCount.setText(goodsCount+"");
                     compluteTotal(goodsCount);
                 }else
                 {
                     ToastUtil.showToast("库存不够");
                 }

                break;
            case R.id.linearLayoutJoin:
                TaskAddCar(goodsCount+"",this,(GBaseActivity) this.context,goodsDetailBean.getItemid(),true);
                break;
            case R.id.imageViewClose:
                dismiss();
                break;
            case R.id.linearLayoutBuy:
                Intent intent =new Intent(context, CheckOrderActivity.class);
                intent.putExtra(CheckOrderActivity.TagItemIDS,goodsDetailBean.getItemid());
                intent.putExtra(CheckOrderActivity.TagType,CheckOrderActivity.TagTypeBuyNow);
                intent.putExtra(CheckOrderActivity.TagNumber,goodsCount+"");
                context.startActivity(intent);

                dismiss();
                break;
        }
    }

    public static void TaskAddCar(String count,final DialogGoodsBuy v,final GBaseActivity activity,String itemID,final boolean isSweetDialog) {
        if (App.getUserBean()==null)
        {
            Intent intent=new Intent(activity, LoginActivity.class);
            activity.startActivity(intent);
            return;
        }else if (App.getUserBean()!=null && App.getUserBean().getIs_verified()!=App.PassValue)
        {
            Intent intent=new Intent(activity,StoreManagerActivity.class);
            activity.startActivity(intent);
            return;
        }
        RequestServerManager.getInstanceDIY().handleMethodDIY(activity, null, false, null,
                Constant.getRootUrl() + Constant.Action.Action_AddCar, Constant.Action.Action_AddCar, RequestServerManager.getInstanceDIY().
                        getRequestParams(Constant.Action.Action_AddCar,App.getUserBean().getUserid(),App.getUserBean().getSession_id(),itemID,count), BaseResponse.class, new ICallBackForRequestServer<BaseResponse>() {
                    @Override
                    public void onSuccess(BaseResponse result) {
                        // JSONObject jsonObject = (JSONObject) result.getData();
                       /* if ( App.getShopCarBeanByID(goodsDetailBean)==null)
                        {
                            ShopCarBean shopCarBean=new ShopCarBean();
                            shopCarBean.setNumber(goodsCount);
                            shopCarBean.setAmount(goodsDetailBean.getAmount());
                            shopCarBean.setItemid(goodsDetailBean.getItemid());
                            shopCarBean.setProduct_spec(goodsDetailBean.getProduct_spec());
                            shopCarBean.setTitle(goodsDetailBean.getTitle());
                            shopCarBean.setShip_price(goodsDetailBean.getPrice());
                            if (App.getShopCarList()==null)
                            {
                                List<ShopCarBean> shopCarBeanList=new ArrayList<com.example.administrator.caigou51.bean.ShopCarBean>();
                                shopCarBeanList.add(shopCarBean);
                                App.saveShopCarList(shopCarBeanList);
                            }else
                            {
                                App.getShopCarList().add(shopCarBean);
                            }
                        }else
                        {
                            App.getShopCarBeanByID(goodsDetailBean).setGoodsCount(goodsCount);
                            App.saveShopCarList(App.getShopCarList());
                        }
*/
                        TaskRefreshSaveShopCarData(false);
                        if (v!=null) {
                            v.dismiss();
                        }
                        if (isSweetDialog)
                        {
                            SweetDialogManager.getInstance().showDialogBySuccessTitleText(activity, "操作成功", "", false, false, new SweetAlertDialog.OnSweetClickListener() {
                                @Override
                                public void onClick(SweetAlertDialog sweetAlertDialog) {

                                    sweetAlertDialog.dismiss();
                                }
                            });
                        }
                    }

                    @Override
                    public void onFail(int type, String errorMsg, String json) {

                    }
                });
    }

    public static void TaskRefreshSaveShopCarData(final boolean isloadmore) {
        RequestServerManager.getInstanceDIY().handleMethodDIY(null, null, isloadmore, null,
                Constant.getRootUrl() + Constant.Action.Action_GetCarList, Constant.Action.Action_GetCarList, RequestServerManager.getInstanceDIY().
                        getRequestParams(Constant.Action.Action_GetCarList,App.getUserBean().getUserid(),App.getUserBean().getSession_id()), BaseResponse.class, new ICallBackForRequestServer<BaseResponse>() {
                    @Override
                    public void onSuccess(BaseResponse result) {
                        // JSONObject jsonObject = (JSONObject) result.getData();
                        List<ShopCarBean> shopCarBeanList = JSON.parseArray(result.getData().toString(), ShopCarBean.class);
                        App.getShopCarList().clear();
                        App.getShopCarList().addAll(shopCarBeanList);
                        App.saveShopCarList(shopCarBeanList);
                        EventBus.getDefault().post(new UpdateShopCarRedCount());
                        EventBus.getDefault().post(new UpdateShopCarFragment());
                    }

                    @Override
                    public void onFail(int type, String errorMsg, String json) {

                    }
                });
    }
}